package com.ctp.gateway.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Created by Lxy on 2025/1/6 18:28
 */
@Configuration
public class HttpGlobalFilter implements GlobalFilter, Ordered {
    private final Logger logger = LoggerFactory.getLogger(HttpGlobalFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // print request info
        String requestPath = exchange.getRequest().getPath().value();
        String method = exchange.getRequest().getMethod().name();
        String remoteAddress = exchange.getRequest().getRemoteAddress().toString();

        logger.info("Request received: {} {}, from {}", method, requestPath, remoteAddress);

        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            // print response info
            Integer status = exchange.getResponse().getStatusCode().value();
            logger.info("Response sent with status code: {}", status);
        }));
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
